package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alipay.sdk.app.PayTask;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.adapter.GV_Recharge_Item_Adapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.base.MyApplication;
import com.jaya.budan.bean.User_Wallet;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.pay.zfb.OrderInfoUtil2_0;
import com.jaya.budan.pay.zfb.PayResult;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.MyGridView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

public class My_Wallet_Recharge_Activity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout back;
    private LinearLayout ll_wx, ll_zfb;
    private Button btn_login;
    private MyGridView gv_my_wallet_recharge;
    private CheckBox cb_register, cb_register2;
    private String access_token;
    private List<User_Wallet> mlist;
    private int tu_id, type = 1;
    private GV_Recharge_Item_Adapter adapter;
    //appid
    public static final String WXAPPID = "wx1228581b153335cb";
    // 商户号
    public static final String WX_MCH_ID = "1603093544";// 自己填写自己项目的
    // API密钥，在商户平台设置
    public static final String WX_API_KEY = "0cf1d0082829d63d4a45f448a3dcf2d3";// 自己填写自己项目的

    /** 支付宝支付业务：入参app_id   2017060707442822  */
    public static final String APPID = "2021001192610758";
    /** 支付宝账户登录授权业务：入参pid值 */
    public static final String PID = "2088812267685045";
    /** 支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "";
    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
    public static final String RSA2_PRIVATE = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkknD+Cjte/HxSKpcf4ICzKMZOGFR3do0vq1nABRbw1REDUf3lZZGryiNeE8sTINGrb0nlTdbsHrqd25H7ckRzOIIu8CVoaOFu6vTpirx0f5aojO+MekHuEWZ2iN092mXlFjiM6reC9OPmmGHVXatnlm8N4/7TbVZgFWUjw103NrD+k8ou+PiLNnyf28DtIbS+IvWJzpBzp6fRUdxFD7VAG3vA0TOFzU3SxzN47iGern8F9dqw61OvgKZnWZTQZttkL6TNyQaJ/TO27RMO3OfLpLDOy5thC8c+n9iSuP0uXAeGoBBkEfYHRo7PGWydivYLQG9BH6V9TvmQ6yBpM2axwIDAQAB";
    public static final String RSA_PRIVATE = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkknD+Cjte/HxSKpcf4ICzKMZOGFR3do0vq1nABRbw1REDUf3lZZGryiNeE8sTINGrb0nlTdbsHrqd25H7ckRzOIIu8CVoaOFu6vTpirx0f5aojO+MekHuEWZ2iN092mXlFjiM6reC9OPmmGHVXatnlm8N4/7TbVZgFWUjw103NrD+k8ou+PiLNnyf28DtIbS+IvWJzpBzp6fRUdxFD7VAG3vA0TOFzU3SxzN47iGern8F9dqw61OvgKZnWZTQZttkL6TNyQaJ/TO27RMO3OfLpLDOy5thC8c+n9iSuP0uXAeGoBBkEfYHRo7PGWydivYLQG9BH6V9TvmQ6yBpM2axwIDAQAB";
    private static final int SDK_PAY_FLAG = 1;
    IWXAPI msgApi = null;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "支付成功");
                        finish();
                    } else if (TextUtils.equals(resultStatus, "8000")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "支付失败");
                    } else{
                        ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "支付取消");
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wallet_recharge);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        //服务器回调接口
        String WX_notifyUrl = RequestConnect.Pay_Url + access_token;// 用于微信支付成功的回调（按自己需求填写）
        back = findViewById(R.id.back);
        btn_login = findViewById(R.id.btn_login);
        cb_register = findViewById(R.id.cb_register);
        cb_register2 = findViewById(R.id.cb_register2);
        ll_wx = findViewById(R.id.ll_wx);
        ll_zfb = findViewById(R.id.ll_zfb);
        gv_my_wallet_recharge = findViewById(R.id.gv_my_wallet_recharge);
        back.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        ll_wx.setOnClickListener(this);
        ll_zfb.setOnClickListener(this);
        gv_my_wallet_recharge.setVerticalSpacing(15);//设置item行间距
        gv_my_wallet_recharge.setHorizontalSpacing(15);
        postData();
        gv_my_wallet_recharge.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelect(position);//选中某一条
                adapter.notifyDataSetChanged();//刷新item
                tu_id = mlist.get(position).getId();
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                JSONObject object = new JSONObject();
                try {
                    object.put("tu_id", tu_id);
                    object.put("pay_type", type);//1 默认支付 2微信 3支付宝
                    object.put("client_id", "1");//客户端 1 android 2 iOS
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                postCZData(object);
                break;
            case R.id.ll_wx:
                type = 2;
                cb_register.setEnabled(true);
                cb_register2.setEnabled(false);
                if (cb_register.isEnabled()){
                    ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "微信支付");
                }
                cb_register.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                cb_register2.setBackgroundResource(R.mipmap.iv_duihao_no);
                break;
            case R.id.ll_zfb:
                type = 3;
                cb_register.setEnabled(false);
                cb_register2.setEnabled(true);
                cb_register.setBackgroundResource(R.mipmap.iv_duihao_no);
                cb_register2.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_my_wallet_Url + access_token + "&type=1", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("wallet", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        mlist = gson.fromJson(info.toString(), new TypeToken<List<User_Wallet>>(){}.getType());
                        adapter = new GV_Recharge_Item_Adapter(My_Wallet_Recharge_Activity.this, mlist, 1);
                        gv_my_wallet_recharge.setAdapter(adapter);
                    } else {
                        ToolUtils.showToast(My_Wallet_Recharge_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postCZData(JSONObject object) {
        Log.d("wallet", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.gr_my_wallet_CZ_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("wallet", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        if (type == 3){
                            //支付宝支付
//                            if (! checkAliPayInstalled(My_Wallet_Recharge_Activity.this)) {
//                                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "请先安装支付宝或者选择其他支付方式");
//                                return;
//                            }
                            if (ToolUtils.isEmpty(APPID) || (ToolUtils.isEmpty(RSA2_PRIVATE) && ToolUtils.isEmpty(RSA_PRIVATE))) {
                                new AlertDialog.Builder(My_Wallet_Recharge_Activity.this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialoginterface, int i) {
                                                finish();
                                            }
                                        }).show();
                                return;
                            }
                            String orderInfo = jsonObject.getString("info");
//                            boolean rsa2 = (RSA2_PRIVATE.length() > 0);
//                            OrderInfoUtil2_0 a = new OrderInfoUtil2_0(access_token);
//                            Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, "0.01元", rsa2, "result");
//                            String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//                            String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
//                            String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//                            final String orderInfo = orderParam + "&" + info;
                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(My_Wallet_Recharge_Activity.this);
                                    Map<String, String> result = alipay.payV2(orderInfo, true);
                                    Log.i("msp", result.toString());
                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        } else {
                            //微信支付
                            if (!isWeixinAvilible(My_Wallet_Recharge_Activity.this)) {
                                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "请先安装微信或者选择其他支付方式");
                                return;
                            }
                            if (msgApi == null) {
                                msgApi = WXAPIFactory.createWXAPI(MyApplication.getInstance(), null);
                                msgApi.registerApp(WXAPPID);// 将该app注册到微信
                            }
                            PayReq req = new PayReq();
//                req.appId = data.getAppid();
//                req.partnerId = data.getPartnerid();
//                req.prepayId = data.getPrepayid();
//                req.nonceStr = data.getNoncestr();
//                req.timeStamp = data.getTimestamp() + "";
//                req.packageValue = data.getPackageX();
//                req.sign = data.getSign();
//                req.extData = MaiLiApplication.getInstance().getUserInfo().getPhone();  微信拓展参数
                            msgApi.sendReq(req);
                        }
                    } else {
                        ToolUtils.showToast(My_Wallet_Recharge_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int code = intent.getIntExtra("result", 1);
        switch (code) {
            case 0://表示成功
                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "wx支付成功");
                finish();
                break;
            case -1://表示失败
                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "wx支付失败");
                break;
            case -2:////表示取消
                ToolUtils.showToast(My_Wallet_Recharge_Activity.this, "wx支付取消");
                break;
            case 1://未知不做处理
                break;
            default:
                break;
        }
    }

    /**
     * 检查微信是否存在
     *
     * @param context
     * @return
     */
    public boolean isWeixinAvilible(Context context) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                Log.d("wallet",i+"----"+pn);
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检查支付包是否存在
     * @param context
     * @return
     */
    private boolean isZfbAvilible(Context context) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                Log.d("wallet",i+"----"+pn);
                if (pn.equals("com.alipay.android.app")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检测是否安装支付宝
     * @param context
     * @return
     */
    public static boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }
}
